import { _decorator, Component, Node, Collider, ITriggerEvent, Prefab, instantiate } from 'cc'
import { Bullet } from '../bullet/Bullet'
import { Constant } from '../framework/Constant'
import { GameManager } from '../framework/GameManager'
const { ccclass, property } = _decorator

const SCOPED = 120
@ccclass('EnemyPlane')
export class EnemyPlane extends Component {
  @property
  moveSpeed = 0.5 // 敌机移动速度

  gameManager: GameManager = null // 游戏节点

  enemyExplode: Prefab = null // 爆炸效果预制

  emitSpace = 0.8 // 子弹发射间隔

  timeRecord = 0 // 子弹时间记录

  isEnemy = false // 是否发射子弹

  bloodVolume = 3 // 血量

  onEnable() {
    // 获取碰撞组件
    const collider = this.getComponent(Collider)
    // 监听开始碰撞
    collider.on('onTriggerEnter', this.onTriggerEnter, this)
  }

  onDisable() {
    const collider = this.getComponent(Collider)
    collider.off('onTriggerEnter', this.onTriggerEnter, this)
  }

  // 碰撞处理
  onTriggerEnter(event: ITriggerEvent) {
    const group = event.otherCollider.getGroup()
    if (group === Constant.collisionGroup.MY_BULLET) {
      const bulletCom = event.otherCollider.getComponent(Bullet)
      this.bloodVolume -= bulletCom.hurt
      if (this.bloodVolume > 0) return
    }
    this.destroyPlane()
  }

  destroyPlane() {
    this.gameManager.addScore(10) // 增加积分
    this.node.destroy() // 销毁节点
    // 播放销毁动画
    let enemyExplode = instantiate(this.enemyExplode)
    let pos = this.node.position
    enemyExplode.setPosition(pos.x, pos.y, pos.z)
    enemyExplode.setParent(this.gameManager.node)
  }

  update(deltaTime: number) {
    this.planeMove()
    this.emitBullet(deltaTime)
  }
  // 飞机移动
  planeMove() {
    let pos = this.node.position
    let ZMove = pos.z + this.moveSpeed
    this.node.setPosition(pos.x, pos.y, ZMove)
    if (ZMove > SCOPED) {
      this.node.destroy()
    }
  }
  // 发射子弹
  emitBullet(deltaTime: number) {
    if (this.isEnemy) {
      this.timeRecord += deltaTime
      if (this.timeRecord > this.emitSpace) {
        this.timeRecord = 0
        this.gameManager.enemyEmitBullet(this.node)
      }
    }
  }
  // 参数1 gameManager节点
  // 参数2 敌机移动速度
  // 参数3 是否发射子弹
  // 参数4 血量
  set(gameManager: GameManager, enemyExplode: Prefab, moveSpeed: number, isEnemy: boolean, bloodVolume: number = 3) {
    this.gameManager = gameManager
    this.enemyExplode = enemyExplode
    this.moveSpeed = moveSpeed
    this.isEnemy = isEnemy
    this.bloodVolume = bloodVolume
  }
}
